import { loginApi, userInfoApi, userInfoDetailApi } from '@/api/user'
import { setToken, getToken, removeToken, setTokenTime } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, data) {
      state.token = data
    },
    // 设置userInfo
    setUserInfo(state, data) {
      state.userInfo = data
    },
    // 清除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 清除userInfo
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 调用登录接口
    async setTokenAsync(ctx, data) {
      const res = await loginApi(data)
      ctx.commit('setToken', res)
      setToken(res)
      setTokenTime()
    },

    // 调用用户信息接口
    async setUserInfo(ctx, data) {
      const res1 = await userInfoApi()
      const res2 = await userInfoDetailApi(res1.userId)
      ctx.commit('setUserInfo', { ...res1, ...res2 })
    },

    // 退出登录
    logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('removeUserInfo')
    }
  }
}
